<?php

namespace app\admin\controller\health\tracking;

use app\common\controller\Backend;
use think\Db;
use think\helper\Arr;

class Monitor extends Backend
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $event  = Db::name('health_tracking_event')->column('id,name,event_code', 'id');
            $params = $this->request->param();
            $where  = [
            ];
            if (!empty($params['create_time']) && is_array($params['create_time']) && count($params['create_time']) === 2) {
                $where['create_time'] = ['between time', [$params['create_time'][0] . ' 00:00:00', $params['create_time'][1] . ' 23:59:59']];
            }
            $paginate = Db::name('health_tracking_monitor')
                ->field('
                    count(id) as total_num,
                    event_id'
                )
                ->where($where)
                ->group('event_id,user_id')
                ->order('event_id', 'desc')
                ->select();
            $lists    = [];
            foreach ($paginate as $datum) {
                if (isset($lists[$datum['event_id']])) {
                    $lists[$datum['event_id']]['total_num']  += $datum['total_num'];
                    $lists[$datum['event_id']]['total_user'] += 1;
                } else {
                    $lists[$datum['event_id']] = [
                        'event_name' => $event[$datum['event_id']]['name'] ?? '',
                        'event_id'   => $datum['event_id'],
                        'total_num'  => $datum['total_num'],
                        'total_user' => 1,
                    ];
                }
            }
            sort($lists);
            $totalNum = array_column($lists, 'total_num'); // 获取年龄列
            array_multisort($totalNum, SORT_DESC, $lists); // 对年龄列进行升序排序
            $data['event_map'] = $event;
            $data['rows']      = $lists;
            $this->success('success', '', $data);
        }
        return $this->view->fetch();
    }
}